package ex02;

import javax.servlet.Servlet;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.net.URLClassLoader;
import java.net.URLStreamHandler;

/**
 * Created by lili on 2017/8/11
 */
public class ServletProcessor1 {

    public void process(Request request, Response response) {

        String uri = request.getUri();
        String servletName = uri.substring(uri.lastIndexOf("/")+1);
        URLClassLoader loader = null;
        try{
            URL[] urls = new URL[1];
            URLStreamHandler streamHandler = null;
            //WEB_ROOT下面的*.class文件
            File classPath = new File(Constants.WEB_ROOT);
            //资源servletclass的位置  file:///yourpath
            String repository = (new URL(
                    "file",
                    null,
                    classPath.getCanonicalPath()+File.separator)).toString();
            urls[0] = new URL(null,repository,streamHandler);
            loader = new URLClassLoader(urls);

        }catch (IOException e){
            System.out.println(e.toString());
        }

        Class myClass = null;

        try {
            //加载类
            myClass = loader.loadClass(servletName);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

        Servlet servlet = null;

        try {
            servlet = (Servlet) myClass.newInstance();
            servlet.service((ServletRequest) request,(ServletResponse) response);
        } catch (Exception e){
            e.printStackTrace();
        } catch (Throwable e){
            e.printStackTrace();
        }


    }

    public static void main(String[] args) throws Exception{
        File classPath = new File(Constants.WEB_ROOT);

        //资源的位置  file:///yourpath
        String repository = (new URL(
                "file",
                null,
                classPath.getCanonicalPath()+File.separator)).toString();

        //file:D:\workinglearn\webroot\
        System.out.println(repository);
    }
}
